Partition Equal Subset Sum
LeetCode 416 | Difficulty: Mediumβ
MediumProblem Descriptionβ
Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
Example 1:
Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
Constraints:
- `1 <= nums.length <= 200`
- `1 <= nums[i] <= 100`
Topics: Array, Dynamic Programming
Approachβ
Dynamic Programmingβ
Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.
When to use
Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).
Solutionsβ
Solution 1: C# (Best: 96 ms)β
| Metric | Value |
|---|---|
| Runtime | 96 ms |
| Memory | 42.1 MB |
| Date | 2021-12-13 |
Solution
public class Solution {
public bool CanPartition(int[] nums) {
int sum = nums.Sum();
int n = nums.Length;
if((sum&1) != 0) return false;
sum /= 2;
bool?[,] memo = new bool?[n+1, sum+1];
return subsetSum(nums, 0, sum, memo);
}
bool subsetSum(int[] nums, int pos, int sum, bool?[,] memo)
{
if(sum == 0) return true;
if(pos>= nums.Length || sum < 0) return false;
if(memo[pos,sum] != null) return memo[pos,sum].Value;
memo[pos,sum] = subsetSum(nums, pos+1, sum-nums[pos], memo) || subsetSum(nums, pos+1, sum, memo);
return memo[pos, sum].Value;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| DP (2D) | $O(n Γ m)$ | $O(n Γ m)$ |
Interview Tipsβ
Key Points
- Discuss the brute force approach first, then optimize. Explain your thought process.
- Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
- Consider if you can reduce space by only keeping the last row/few values.